package com.hrt.web.product.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hrt.base.BaseController;
import com.hrt.bean.AddressBook;
import com.hrt.bean.GiftDetail;
import com.hrt.bean.GiftInfor;
import com.hrt.bean.HRTMember;
import com.hrt.bean.OrderDetail;
import com.hrt.bean.OrderInfor;
import com.hrt.bean.ShoppingCar;
import com.hrt.manage.sequence.service.SequenceService;
import com.hrt.web.addressBook.service.AddressBookService;
import com.hrt.web.comments.service.CommentsWebService;
import com.hrt.web.member.service.HRTMemberService;
import com.hrt.web.product.service.GiftDetailService;
import com.hrt.web.product.service.GiftInforService;
import com.hrt.web.product.service.GiftTypeWebService;
import com.hrt.web.shoppingCar.service.ShoppingCarService;

@Controller
public class GiftInforControllorWeb extends BaseController<GiftInfor> {
	
	/**礼品基本信息*/
	@Autowired
	private GiftInforService giftInforService;
	
	//礼品详情
	@Autowired
	private GiftDetailService giftDetailService;
	
	//会员
	@Autowired
	private HRTMemberService hrtMemberService;
	
	//地址本
	@Autowired
	private AddressBookService addressBookService;
	
	//购物车
	@Autowired
	private ShoppingCarService shoppingCarService;
	
	//序列
	@Autowired
	private SequenceService sequenceService;
	
	//评论
	@Autowired
	private CommentsWebService commentsWebService;
	
	/**礼品分类*/
	@Autowired
	private GiftTypeWebService giftTypeWebService;
	
	/**
	 * 首页的倒叙排序前八条记录
	 * */
	@RequestMapping(value = "/index")
	public ModelAndView list(){
		ModelAndView mav = new ModelAndView();
		List<GiftInfor> list = this.giftInforService.searchofeight();
		mav.addObject("list",list);
		mav.setViewName("/index");
		return mav;
		
	}
	
	/**
	 * 分页
	 * *//*
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/HRTWEB/queryByPage2")
	@ResponseBody
	public Map queryByPage(
			@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
			@RequestParam(value = "pageSize", required = false) Integer pageSize,
			HttpServletRequest request) {
		Map resultMap = new HashMap();

		if (pageSize == null || "".equals(pageSize)) {
			pageSize = 12;
		}
		if (pageIndex == null || "".equals(pageIndex)) {
			pageIndex = 1;
		}
		setPageIndex(pageIndex);

		setPageSize(pageSize);

		setTotalCount(giftInforService.totalCount());

		List<GiftInfor> resultList = giftInforService.queryByPage(getPageIndex(),
				getPageSize());
		setList(resultList);

		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));

		page = this.getPage();

		resultMap.put("pageResult", page);
		return resultMap;
	}

	*//**
	 * 查看
	 * 
	 *//*
	@SuppressWarnings("null")
	@RequestMapping(value = "/HRTWEB/product_index")
	public ModelAndView productIndex(HttpServletRequest request) {
		ModelAndView view = new ModelAndView();
		setPageSize(12);
		list = giftInforService.queryByPage(getPageIndex(), getPageSize());
		setTotalCount(giftInforService.totalCount());
		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));

		page = this.getPage();
		
		List<GiftType> typeWebList = giftTypeWebService.findDelParents();
		if(typeWebList != null || typeWebList.size() > 0){
			for(GiftType type : typeWebList){
				List<GiftType> typeSonWebList = giftTypeWebService.findDelSonById(type.getId());
				type.setSonType(typeSonWebList);
			}
		}
		view.addObject("pageResult", page);
		view.addObject("parentsList", typeWebList);
//		view.addObject("sonList", typeSonWebList);
		return view;

	}*/
	
	/**
	 * 详情页面
	 * */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/HRTWEB/details/details")
	@ResponseBody
	public ModelAndView detailGI(
			@RequestParam(value = "id", required = true) String giId,
			HttpServletRequest request, HttpServletResponse response){
		ModelAndView view = new ModelAndView();
		GiftInfor gi = null;
		List<String> detailList = new ArrayList<String> ();
		List<GiftDetail> giftDetails = new ArrayList<GiftDetail>();
		
		//上传图片
		List<String> picGiftImg = new ArrayList<String>();
		//存放第一张图片路径
		String fistImg = "";
		
		//用来拼接礼品规格id的字符串
		String gdeIds="";
		
		if (giId != null && !"".equals(giId)) {
			gi = this.giftInforService.getById(new Long(giId));
			detailList = this.giftDetailService.getDetailIdforId(new Long(giId));
			
			//多图片上传
			String picStr = gi.getDetail();
			if(picStr!=null && picStr!="" ){
				String[] picStrArr = picStr.split(",");
//				List<String> picList = new ArrayList<String>();
				for(int f = 0 ;f <picStrArr.length ; f++){
					fistImg = picStrArr[0];
					picGiftImg.add(picStrArr[f]);
				}
			}
			
			//通过礼品id获取礼品详情的集合
			giftDetails = this.giftDetailService.getDetailByGI(Long.parseLong(giId));
			//通过礼品详情的集合，拿到礼品详情的id
			for(GiftDetail gde : giftDetails){
				gdeIds = gdeIds+gde.getId()+",";
			}
			
			byte[] buf = gi.getUeditorDetails();
			try {
				String strBuf = new String(buf, "UTF-8");
				gi.setDetails_Str(strBuf);
				
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		
		//去掉字符串的最后一个分号
		if(gdeIds != null && gdeIds != ""){
			gdeIds=gdeIds.substring(0,gdeIds.length()-1);
		}
		System.out.println("sdfgshf-----gdeIds-------->"+gdeIds);
		if(gdeIds==""){
			gdeIds="0";
		}
		//全部评论
//		setTotalCount((long)1);
		List  resultList= new ArrayList();
		if(gdeIds==null || gdeIds==""){
			throw new RuntimeException("礼品规格id有误");
		}else{
			List<Long> gdeIdsList = commentsWebService.findCommIdByGdeId(gdeIds);
			String gdeIdstr = "";
			if(gdeIdsList!=null && gdeIdsList.size()>0){
				for(Long sonId : gdeIdsList ){
					gdeIdstr = gdeIdstr+sonId+",";
				}
				if(gdeIdstr != ""){
					gdeIdstr=gdeIdstr.substring(0,gdeIdstr.length()-1);
				}
				
				resultList = commentsWebService.queryById(gdeIdstr, this.getPageIndex(),
						this.getPageSize(),"1");
				
				setTotalCount(commentsWebService.findNumByGdeId(gdeIdstr));
			}
		}
		this.setList(resultList);
		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));
//		System.out.println("2=="+this.getTotalCount()+","+this.getPageSize());
		page = this.getPage();
		view.addObject("giftDetails", giftDetails);
		view.addObject("pageResult", page);
		//---------------全部评论结束-----------
		int gdeLen = 0;
		if(giftDetails!=null && giftDetails.size()>0){
			gdeLen = giftDetails.size();
		}
		
		//第一张图片
		view.addObject("fistImg", fistImg);
		
		//上传图片（页面）
		view.addObject("picGiftImg", picGiftImg);
		//礼品详情的长度
		view.addObject("gdeLen", gdeLen);
		view.addObject("detailList", detailList);
		view.addObject("detailGI", gi);
		return view;
	}
	

	/**
	 * 查找
	 * 
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/HRTWEB/find")
	@ResponseBody
	public Map findDetail(@RequestParam(value = "giftId", required = true) Long giftId,
			@RequestParam(value = "color", required = false) String colorName,
			HttpServletRequest request) {
		Map result = new HashMap();
		String color = null;
		try {
			color = new String(colorName.getBytes("iso-8859-1"),"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		List<GiftDetail> gdDetail = this.giftDetailService.getColorAndGI(giftId, color.trim());
		result.put("gdDetail", gdDetail);
		return result;
		
		

	}
	/**
	 * 根据giftId查找礼品规格
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/HRTWEB/findAll")
	@ResponseBody
	public Map findAll(@RequestParam(value = "giftId", required = true) Long giftId,
			HttpServletRequest request) {
		Map result = new HashMap();
		
		List<GiftDetail> gdDetail = this.giftDetailService.getDetailByGI(giftId);
		result.put("gdDetail", gdDetail);
		return result;
		
		

	}
	/**
	 * 根据giftId查找礼品规格
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/HRTWEB/findByGdName")
	@ResponseBody
	public Map findByGdName(@RequestParam(value = "giftId", required = true) Long giftId,
			@RequestParam(value = "gdName", required = false) String gdName,
			HttpServletRequest request) {
		Map result = new HashMap();
		System.out.println("gdName---------->"+gdName);
		GiftDetail detail = this.giftDetailService.getByGiftIdAndName(giftId, gdName);
		result.put("detail", detail);
		return result;
		
		
	}
	/**
	 * 立即购买 vs 加入购物车
	 */
	@RequestMapping(value = "/HRTWEB/buyGift")
	@ResponseBody
	public ModelAndView buyGift(@RequestParam(value = "shopType", required = true) Long shopType,
			@RequestParam(value = "qty_item_1", required = false) Integer total,
			@RequestParam(value = "giftId", required = false) Long giftId,
			@RequestParam(value = "memberId", required = false) Long memberId,
			@RequestParam(value = "gdName", required = false) String gdName,
			HttpServletRequest request,HttpServletResponse response) {
		ModelAndView view = new ModelAndView();
		
		GiftDetail giftDetail = this.giftDetailService.getByGiftIdAndName(giftId, gdName);
		Double salePrice = giftDetail.getSalePrice();
		Double summery = total*salePrice;
		HRTMember hrtMember = hrtMemberService.getMemberByid(memberId);
		List<Long> carIds = new ArrayList<Long>();
		List<ShoppingCar> carList = shoppingCarService.getShoppingCarByMemberId(memberId);
		for(ShoppingCar car:carList){
			carIds.add(car.getGiDetailId());
		}
		//立即购买
		if(shopType.equals(new Long(1))){
			List<AddressBook> addressList = addressBookService.getAddListById(memberId);
			//获取默认地址
			AddressBook address = addressBookService.getDefaultAddress(memberId,new Integer(1));
			OrderDetail detail = new OrderDetail();
			detail.setGiftDetail(giftDetail);
			detail.setSalePrice(salePrice);
			detail.setTotal(total);
			detail.setSummery(summery);
			//订单编号
			String orderCode = sequenceService.getNextSequence(OrderInfor.class);
			view.addObject("orderCode", orderCode);
			view.addObject("detail", detail);
			view.addObject("giftDetail", giftDetail);
			view.addObject("hrtMember", hrtMember);
			view.addObject("shopType", shopType);
			view.addObject("addressList", addressList);
			view.addObject("address", address);
			view.setViewName("/HRTWEB/buyGift");
		}
		
		
		//加入购物车
		else{
			
			if(!carIds.contains(giftDetail.getId())){
				
				ShoppingCar car = new ShoppingCar();
				car.setAddTime(shoppingCarService.getDate());//加入购物车时间
				car.setTotal(total);//礼品规格数量
				car.setSummery(summery);//订单金额
				car.setGiDetailId(giftDetail.getId());//礼品规格id
				car.setGiftId(giftDetail.getGiftId());//礼品id
				car.setGiftName(giftDetail.getGiftName());//礼品名称
				car.setGiDetailName(giftDetail.getGdName());//礼品规格名称
				car.setSalePrice(giftDetail.getSalePrice());//礼品规格单价
				car.setMemberId(memberId);
				car.setGiftDetail(giftDetail);
				car.setHrtMember(hrtMember);
				
				try {
					shoppingCarService.saveCar(car);
				} catch (Exception e) {
					e.printStackTrace();
				}
				carList = shoppingCarService.getShoppingCarByMemberId(memberId);
				view.addObject("carList", carList);
				
				
			}
			else{
				ShoppingCar car = shoppingCarService.getCarByMbrAndGI(memberId,giftDetail.getId());
				Integer tol = car.getTotal();
				car.setTotal(tol+total);
				shoppingCarService.updateCar(car);
				carList = shoppingCarService.getShoppingCarByMemberId(memberId);
				view.addObject("carList", carList);
			}
			
			
			view.setViewName("redirect:/web/shoppingCar/list.do?memberId="+memberId);
			
		}
		return view;
		
		
	}
	/**
	 * 购物车下单
	 */
	@RequestMapping(value = "/HRTWEB/shoppingCar")
	@ResponseBody
	public ModelAndView shoppingCar(
			@RequestParam(value = "ids", required = true) String ids,
			@RequestParam(value = "memberId", required = true) Long memberId,
			HttpServletRequest request,HttpServletResponse response) {
		Long[] idArr = null;
		ModelAndView view = new ModelAndView();
		if (ids != null) {
			if (ids.indexOf(",") != -1) {
				String[] idStrs = ids.split(",");
				idArr = new Long[idStrs.length];
				for (int idx = 0; idx < idStrs.length; idx++) {
					idArr[idx] = Long.parseLong(idStrs[idx]);
				}
			} else {
				idArr = new Long[] { Long.parseLong(ids) };
			}

		}
		
		//获取默认地址
		AddressBook address = addressBookService.getDefaultAddress(memberId, 1);
		
		HRTMember hrtMember = hrtMemberService.getMemberByid(memberId);
		List<AddressBook> addressList = addressBookService.getAddListById(memberId);
		List<ShoppingCar> carList = new ArrayList<ShoppingCar>();
		List<GiftDetail> giftDetailList = new ArrayList<GiftDetail>();
		List<OrderDetail> orderDetailList = new ArrayList<OrderDetail>();
		Double orderSummery = 0.0;
		for(int i=0;i<idArr.length;i++){
			ShoppingCar car  = shoppingCarService.getCarById(idArr[i]);
			orderSummery =orderSummery +car.getSummery();
			car.setIsdelete(1);
			shoppingCarService.updateCar(car);
			carList.add(car);
			
			GiftDetail gf = giftDetailService.getGiftDetailById(car.getGiDetailId());
			giftDetailList.add(gf);
			
			OrderDetail orderDetail = new OrderDetail();
			orderDetail.setGiftDetail(gf);
			orderDetail.setGiftDetailId(car.getGiDetailId());
			orderDetail.setGdName(car.getGiDetailName());
			
			orderDetail.setTotal(car.getTotal());
			orderDetail.setSalePrice(car.getSalePrice());
			orderDetail.setSummery(car.getSummery());
			orderDetailList.add(orderDetail);
		}
		//订单编号
		String orderCode = sequenceService.getNextSequence(OrderInfor.class);
		view.addObject("orderCode", orderCode);
		view.addObject("orderSummery", orderSummery);
		view.addObject("hrtMember", hrtMember);
		view.addObject("addressList", addressList);
		view.addObject("address", address);
		view.addObject("giftDetailList", giftDetailList);
		view.addObject("orderDetailList", orderDetailList);
		view.setViewName("/HRTWEB/buyCar");
		return view;
		
		
	}
	@RequestMapping(value = "/HRTWEB/deleteAll", method = RequestMethod.POST)
	public @ResponseBody Long[] deleteAll(
			@RequestParam(value = "ids", required = true) String ids,
			HttpServletResponse response) throws IOException {
		Long[] idArr = null;
		if (ids != null) {
			if (ids.indexOf(",") != -1) {
				String[] idStrs = ids.split(",");
				idArr = new Long[idStrs.length];
				for (int idx = 0; idx < idStrs.length; idx++) {
					idArr[idx] = Long.parseLong(idStrs[idx]);
				}
			} else {
				idArr = new Long[] { Long.parseLong(ids) };
			}

		}
		try {
			shoppingCarService.deleteById(idArr);
			return idArr;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

}
